import React, { useState, useEffect } from "react";
import { View, StyleSheet, Dimensions, Text, StatusBar, TouchableOpacity, Image, ScrollView, RefreshControl, Clipboard, AppState } from "react-native";
import { Shadow } from 'react-native-shadow-2';
import { useIsFocused } from '@react-navigation/native';
import { useSelector, useDispatch } from "react-redux";
import Toast from 'react-native-simple-toast'
import { getValue } from "@/utils/deviceStorage";
import { AssetList } from '@/config/config'
import { getETHBalance, getERC20Balance } from '@/utils/transfer'
import { getLabel } from "@/utils/util";
import Loading from "@/components/LoadingModal";
import LockScreenEnter from '@/components/LockScreenEnter'
import CommonContext from '@/utils/createContext'

const { width, scale } = Dimensions.get('window')
const ratio = width * scale / 1080

const Main = (props) => {

    const dispatch = useDispatch()
    const isFocused = useIsFocused()
    const [appState, setAppState] = useState(AppState.currentState)
    const [lastAppState, setLastAppState] = useState('')
    const [coinType, setCoinType] = useState('')
    const [loadingVisible, setLoadingVisible] = useState(false)
    const [selectedWallet, setSelectedWallet] = useState({})
    const [allAssetList, setAllAssetList] = useState([])
    const [someAssetList, setSomeAssetSomeList] = useState([])
    const [assetTitle, setAssetTitle] = useState('Show all assets')
    const [refreshing, setRefreshing] = useState(false)
    const modalVisible = useSelector((state) => state.singleSignReducer.lockVisible);

    useEffect(() => {
        AppState.addEventListener('change', handleAppStateChange);
    }, [])

    useEffect(() => {
        if (!modalVisible && isFocused) {
            let str = getValue('coinType')
            let obj = getValue('selectedWallet')
            setCoinType(str)
            setSelectedWallet(obj || {})
            setLoadingVisible(true)
            getAssetList(obj).then(() => setLoadingVisible(false))
        }
    }, [modalVisible, isFocused]);

    useEffect(() => {
        if (lastAppState.match(/inactive|background/) && appState === 'active') {
            // dispatch({ type: "setLockVisible", value: true });
        }
    }, [appState, lastAppState])

    const handleAppStateChange = (value) => {
        if (value === 'active') {
            setLastAppState('background')
        }
        setAppState(value)
    }

    const handleClose = () => {
        dispatch({ type: "setLockVisible", value: false });
    }

    const setModalVisible = (visible) => {
        dispatch({ type: "setLockVisible", value: visible });
    }

    const getAssetList = async (obj) => {
        if (obj && obj.address) {
            let amount
            let arr = AssetList
            for (let i = 0; i < arr.length; i++) {
                let label = arr[i].label
                switch (label) {
                    case 'ETH':
                        amount = await getETHBalance(obj.address)
                        break;
                    case 'USDT':
                        amount = await getERC20Balance(obj.address)
                        break;
                    default:
                        break;
                }
                arr[i].amount = amount
            }
            let arr1 = arr.filter((item) => {
                if (item.label == 'ETH') {
                    return true
                } else {
                    return item && parseFloat(item.amount) && parseFloat(item.amount) > 0;
                }
            });
            setAllAssetList(arr)
            setSomeAssetSomeList(arr1)
        }
    }

    const handlePressCoin = () => {
        props.navigation.navigate('coin-select')
    }

    const handlePressSafe = () => {
        let list = getValue('safeWalletList')
        if (list && list.length > 0) {
            props.navigation.navigate('safe-have-account')
        } else {
            props.navigation.navigate('safe-no-account')
        }
    }

    const handlePressExchange = () => {
        props.navigation.navigate('address-manage')
    }

    const handlePressCopy = () => {
        Clipboard.setString(selectedWallet.address)
        Toast.showWithGravity(
            'Address copied to clipboard',
            Toast.SHORT,
            Toast.CENTER)
    }

    const handlePressSend = () => {
        props.navigation.navigate({
            name: 'send',
            params: {
                source: 'main'
            }
        })
    }

    const handlePressReceive = () => {
        props.navigation.navigate({
            name: 'receive',
            params: {
                source: 'main'
            }
        })
    }

    const handlePressPlus = () => {
        props.navigation.navigate('coin-add')
    }

    const onRefresh = async () => {
        setRefreshing(true)
        await getAssetList(selectedWallet)
        setRefreshing(false)
    }

    const handlePressAsset = (item) => {
        props.navigation.navigate({
            name: 'assets',
            params: {
                assetInfo: item
            }
        })
    }

    return (
        <View style={styles.container}>
            <StatusBar backgroundColor='#F5F6FA' barStyle='dark-content' />
            <ScrollView refreshControl={<RefreshControl
                refreshing={refreshing}
                onRefresh={onRefresh} />}
                contentContainerStyle={styles.bodyContent}>
                <View style={{ flexDirection: 'row', justifyContent: 'space-between', width: width }}>
                    <View style={{ marginLeft: 15 * ratio }}>
                        <Shadow offset={[0, 2]}
                            distance={0} startColor='rgba(0,0,0,0.25)' finalColor='transparent' radius={3.84}>
                            <TouchableOpacity style={styles.changeCoin} onPress={handlePressCoin}>
                                <Image source={require('@/assets/imgs/icon.png')}
                                    style={{ width: 15 * ratio, height: 15 * ratio, marginLeft: 11 * ratio }} />
                                <Text style={{ ...styles.title1, marginLeft: 7 * ratio }}>{coinType}</Text>
                                <Image source={require('@/assets/imgs/choose.png')}
                                    style={{ width: 8 * ratio, height: 5 * ratio, marginLeft: 10 * ratio }} />
                            </TouchableOpacity>
                        </Shadow>
                    </View>
                    <TouchableOpacity onPress={handlePressSafe} style={{ flexDirection: 'row', alignItems: 'center' }}>
                        <Image source={require('@/assets/imgs/to_safe.png')}
                            style={{ width: 16 * ratio, height: 12 * ratio, marginRight: 2 * ratio }} />
                        <Text style={styles.title7}>Safe</Text>
                    </TouchableOpacity>
                </View>
                <View style={{ marginTop: 24 * ratio }}>
                    <Shadow offset={[0, 2]}
                        distance={0} startColor='rgba(0,0,0,0.25)' finalColor='transparent' radius={3.84}>
                        <View style={styles.walletContent}>
                            <View style={{ flexDirection: 'row', justifyContent: 'space-between', alignItems: 'center', width: 330 * ratio, marginTop: 19 * ratio }}>
                                <View style={{ flexDirection: 'row', alignItems: 'center' }}>
                                    <Text style={{ ...styles.title1, width: 136 * ratio, marginLeft: 18 * ratio }} numberOfLines={1} ellipsizeMode='middle'>
                                        {selectedWallet.address}
                                    </Text>
                                    <TouchableOpacity style={styles.button1} onPress={handlePressExchange}>
                                        <Text style={styles.title2}>Exchange</Text>
                                    </TouchableOpacity>
                                </View>
                                <TouchableOpacity onPress={handlePressCopy}>
                                    <Image source={require('@/assets/imgs/copy.png')}
                                        style={{ width: 12 * ratio, height: 12 * ratio, marginRight: 27 * ratio }} />
                                </TouchableOpacity>
                            </View>
                            <View style={styles.profileContent}>
                                <Image source={require('@/assets/imgs/loadingx2.png')}
                                    style={{ width: 23 * ratio, height: 23 * ratio }} />
                            </View>
                            <View style={styles.buttonContent}>
                                <TouchableOpacity onPress={handlePressSend}
                                    style={{ flex: 5, flexDirection: 'row', justifyContent: 'center', alignItems: 'center' }}>
                                    <Image source={require('@/assets/imgs/payfor.png')}
                                        style={{ width: 18 * ratio, height: 18 * ratio }} />
                                    <Text style={{ ...styles.title1, marginLeft: 12 * ratio }}>Send</Text>
                                </TouchableOpacity>
                                <View style={styles.divider1}></View>
                                <TouchableOpacity onPress={handlePressReceive}
                                    style={{ flex: 5, flexDirection: 'row', justifyContent: 'center', alignItems: 'center' }}>
                                    <Image source={require('@/assets/imgs/inall.png')}
                                        style={{ width: 18 * ratio, height: 18 * ratio }} />
                                    <Text style={{ ...styles.title1, marginLeft: 12 * ratio }}>Receive</Text>
                                </TouchableOpacity>
                            </View>
                        </View>
                    </Shadow>
                </View>
                <View style={{ marginTop: 12 * ratio }}>
                    <Shadow offset={[0, 2]}
                        distance={0} startColor='rgba(0,0,0,0.25)' finalColor='transparent' radius={3.84}>
                        <View style={styles.assetContent}>
                            <View style={{ flexDirection: 'row', marginTop: 14 * ratio, alignItems: 'center', justifyContent: 'space-between' }}>
                                <View style={{ flexDirection: 'row', alignItems: 'center' }}>
                                    <Text style={{ ...styles.title3, marginLeft: 19 * ratio }}>Assets</Text>
                                    {assetTitle == 'Show all assets' ? <TouchableOpacity onPress={() => { setAssetTitle('Show some assets') }}>
                                        <Image source={require('@/assets/imgs/showsd.png')}
                                            style={{ width: 19 * ratio, height: 19 * ratio, marginLeft: 4 * ratio }} />
                                    </TouchableOpacity> :
                                        <TouchableOpacity onPress={() => { setAssetTitle('Show all assets') }}>
                                            <Image source={require('@/assets/imgs/showsss.png')}
                                                style={{ width: 19 * ratio, height: 19 * ratio, marginLeft: 4 * ratio }} />
                                        </TouchableOpacity>}
                                    <Text style={{ ...styles.title4, marginLeft: 4 * ratio }}>{assetTitle}</Text>
                                </View>
                                <TouchableOpacity onPress={handlePressPlus}>
                                    <Image source={require('@/assets/imgs/add.png')}
                                        style={{ width: 24 * ratio, height: 24 * ratio, marginRight: 12 * ratio }} />
                                </TouchableOpacity>
                            </View>
                            <View style={{ minHeight: 10 * ratio }}>
                                {assetTitle === 'Show all assets' ?
                                    allAssetList && allAssetList.map((item, index) => {
                                        let isLastItem = false
                                        if (index == allAssetList.length - 1) {
                                            isLastItem = true
                                        }
                                        return (
                                            <View key={index} style={{ justifyContent: 'center', alignItems: 'center' }}>
                                                <TouchableOpacity style={styles.itemContent} onPress={() => { handlePressAsset(item) }}>
                                                    <View style={{ flexDirection: 'row', marginLeft: 18 * ratio }}>
                                                        <View style={styles.logoContent}>
                                                            <Image source={item.profileImg}
                                                                style={{ width: 12 * ratio, height: 12 * ratio }} />
                                                        </View>
                                                        <Text style={{ ...styles.title3, marginLeft: 4 * ratio }}>{getLabel(item.label)}</Text>
                                                    </View>
                                                    <View style={{ flexDirection: 'row', marginRight: 12 * ratio, alignItems: 'flex-end' }}>
                                                        <Text style={{ ...styles.title5 }}>{item.amount && item.amount.substring(0, 4) || '0.00'}</Text>
                                                        <Text style={{ ...styles.title2, color: '#2A2A2A' }}>{item.amount && item.amount.substring(4, 9)}</Text>
                                                    </View>
                                                </TouchableOpacity>
                                                {!isLastItem && <View style={styles.divider2}></View>}
                                            </View>
                                        )
                                    }) :
                                    someAssetList && someAssetList.map((item, index) => {
                                        let isLastItem = false
                                        if (index == someAssetList.length - 1) {
                                            isLastItem = true
                                        }
                                        return (
                                            <View key={index} style={{ justifyContent: 'center', alignItems: 'center' }}>
                                                <View style={styles.itemContent}>
                                                    <View style={{ flexDirection: 'row', marginLeft: 18 * ratio }}>
                                                        <View style={styles.logoContent}>
                                                            <Image source={item.profileImg}
                                                                style={{ width: 12 * ratio, height: 12 * ratio }} />
                                                        </View>
                                                        <Text style={{ ...styles.title3, marginLeft: 4 * ratio }}>{getLabel(item.label)}</Text>
                                                    </View>
                                                    <View style={{ flexDirection: 'row', marginRight: 12 * ratio, alignItems: 'flex-end' }}>
                                                        <Text style={{ ...styles.title5 }}>{item.amount && item.amount.substring(0, 4)}</Text>
                                                        <Text style={{ ...styles.title2, color: '#2A2A2A' }}>{item.amount && item.amount.substring(4, 9)}</Text>
                                                    </View>
                                                </View>
                                                {!isLastItem && <View style={styles.divider2}></View>}
                                            </View>
                                        )
                                    })}
                            </View>
                        </View>
                    </Shadow>
                </View>
                <View style={{ flex: 1, justifyContent: 'flex-end', marginBottom: 40 * ratio }}>
                    <View style={{ flexDirection: 'row' }}>
                        <Image source={require('@/assets/imgs/logo.png')} style={{ width: 20 * ratio, height: 18 * ratio }} />
                        <Text style={styles.title6}>Sectoken</Text>
                    </View>
                </View>
            </ScrollView>
            {modalVisible && <CommonContext.Provider value={{ modalVisible, setModalVisible, handleClose }}>
                <LockScreenEnter {...props} />
            </CommonContext.Provider>}
            {loadingVisible && <Loading visible={loadingVisible} />}
        </View>
    )
}

const styles = StyleSheet.create({
    container: {
        flex: 1,
        backgroundColor: '#F5F6FA'
    },
    bodyContent: {
        flex: 1,
        alignItems: 'center',
        marginTop: 15 * ratio
    },
    changeCoin: {
        width: 82 * ratio,
        height: 20 * ratio,
        backgroundColor: '#5B6DFD',
        borderRadius: 7,
        borderWidth: 1,
        borderColor: '#FFFFFF',
        flexDirection: 'row',
        alignItems: 'center'
    },
    walletContent: {
        width: 330 * ratio,
        height: 133 * ratio,
        backgroundColor: '#5B6DFD',
        borderRadius: 8,
        alignItems: 'center'
    },
    profileContent: {
        width: 40 * ratio,
        height: 40 * ratio,
        backgroundColor: '#FFFFFF',
        borderRadius: 50,
        marginTop: 3 * ratio,
        justifyContent: 'center',
        alignItems: 'center'
    },
    buttonContent: {
        width: 330 * ratio,
        marginTop: 12 * ratio,
        flexDirection: 'row',
        justifyContent: 'space-between',
        alignItems: 'center'
    },
    assetContent: {
        width: 330 * ratio,
        backgroundColor: '#FFFFFF',
        borderRadius: 8,
        elevation: 5,
        minHeight: 134 * ratio
    },
    itemContent: {
        width: 330 * ratio,
        height: 50 * ratio,
        flexDirection: 'row',
        alignItems: 'center',
        justifyContent: 'space-between'
    },
    logoContent: {
        width: 20 * ratio,
        height: 20 * ratio,
        backgroundColor: '#5B6DFD',
        borderRadius: 50,
        justifyContent: 'center',
        alignItems: 'center'
    },
    title1: {
        fontSize: 13,
        fontFamily: 'Microsoft YaHei',
        fontWeight: '400',
        color: '#FFFFFF',
        lineHeight: 17
    },
    title2: {
        fontSize: 10,
        fontFamily: 'Microsoft YaHei',
        fontWeight: '400',
        color: '#FFFFFF',
        lineHeight: 13
    },
    title4: {
        fontSize: 12,
        fontFamily: 'Microsoft YaHei',
        fontWeight: '400',
        color: '#A6A6A6',
        lineHeight: 15
    },
    title3: {
        fontSize: 14,
        fontFamily: 'SimHei',
        fontWeight: '400',
        color: '#2A2A2A',
        lineHeight: 19
    },
    title5: {
        fontSize: 15,
        fontFamily: 'Microsoft YaHei',
        fontWeight: '400',
        color: '#2A2A2A',
        lineHeight: 20
    },
    title6: {
        fontSize: 14,
        fontFamily: 'Microsoft YaHei',
        fontWeight: 'bold',
        color: '#DADAE3',
        lineHeight: 19,
        marginLeft: 7 * ratio
    },
    title7: {
        fontSize: 16,
        fontFamily: 'PingFangSC-Medium, PingFang SC',
        fontWeight: '500',
        color: '#0069F6',
        lineHeight: 22,
        marginRight: 17 * ratio
    },
    button1: {
        width: 50 * ratio,
        height: 20 * ratio,
        borderWidth: 1,
        borderColor: '#FFFFFF',
        borderRadius: 9,
        justifyContent: 'center',
        alignItems: 'center',
        marginLeft: 3 * ratio
    },
    divider1: {
        width: 0,
        height: 36 * ratio,
        borderColor: '#FFFFFF',
        borderWidth: 1,
        opacity: 0.61,
        elevation: 5,
    },
    divider2: {
        width: 300 * ratio,
        height: 0,
        borderColor: '#EFEFEF',
        borderWidth: 1
    }
})
export default Main